//! # 键位状态
//!
//! 用于映射器使用过程中的状态记录

use crate::driver::keyboard::{key_code::KeyCode, KeyboardDriver, KeyboardDriverFunctions};

/// 键位状态
pub struct KeyState {
    /// [`KeyCode`] 序列，顺序按下，逆序松开
    pub key_codes: Vec<KeyCode>,
    /// 是否被按下
    pub pressed: bool,
}

impl KeyState {
    /// 根据 [`KeyCode`] 创建 [`KeyState`]
    pub fn new(key_codes: Vec<KeyCode>) -> Self {
        Self {
            key_codes,
            pressed: false,
        }
    }

    /// 根据 key_codes 顺序按下按键
    pub fn keys_down(&mut self, driver: &KeyboardDriver) {
        // 如果未释放，则先释放按键
        if self.pressed {
            self.keys_up(driver);
        }

        // 按下按键
        for key_code in &self.key_codes {
            driver.key_down(key_code.clone());
        }
        self.pressed = true;
    }

    /// 根据 key_codes 逆序释放按键
    pub fn keys_up(&mut self, driver: &KeyboardDriver) {
        for key_code in self.key_codes.iter().rev() {
            driver.key_up(key_code.clone());
        }
        self.pressed = false;
    }
}
